<template>
  <div>
    <el-dialog :before-close="handleClose" :title="computedTitle" :visible.sync="isOpen" width="500px">
      <el-form ref="deptFormRef" :model="deptForm" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="deptForm.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="deptForm.managerId" placeholder="请选择负责人" style="width: 100%" value="">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="deptForm.introduce" :rows="4" placeholder="请输入内容" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="isLoading" style="width: 100px;" type="primary" @click="handleSubmit">确认</el-button>
          <el-button style="width: 100px;" @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  departmentListService,
  departmentManagerListService,
  departmentAddService,
  departmentDetailService,
  departmentUpdateService,
  departmentDeleteService
} from '@/api/department'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      isOpen: false, // 控制弹框的显示与隐藏
      isLoading: false, // 控制按钮的加载状态
      eventType: '', // 处理事件的类型
      currentNodeId: '', // 当前操作的部门ID
      verifyTempData: {}, // 用于校验表单的临时数据
      // 添加部门表单数据
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        managerId: '', // 部门负责人ID
        introduce: '', // 部门介绍
        pid: '' // 父级部门ID
      },
      // 添加部门表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            trigger: 'blur', validator: async(rule, value, callback) => {
              if (this.eventType === 'edit') {
                this.verifyTempData = this.verifyTempData.filter(item => item.id !== this.currentNodeId)
              }
              if (this.verifyTempData.some(item => item.name === value)) {
                callback(new Error('该部门名称已存在'))
              } else {
                callback()
              }
            }
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            trigger: 'blur', validator: async(rule, value, callback) => {
              if (this.eventType === 'edit') {
                this.verifyTempData = this.verifyTempData.filter(item => item.id !== this.currentNodeId)
              }
              if (this.verifyTempData.some(item => item.code === value)) {
                callback(new Error('该部门编码已存在'))
                this.isLoading = false
              } else {
                callback()
              }
            }
          }
        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 部门负责人数据
      managerList: []
    }
  },
  computed: {
    // 动态显示标题
    computedTitle() {
      return this.eventType === 'add' ? '添加部门' : '编辑部门信息'
    }
  },
  methods: {
    // 显示弹框时的初始化操作
    async showDialog(id, type) {
      this.isOpen = true
      this.currentNodeId = id
      this.eventType = type
      // 用于校验表单的临时数据
      this.verifyTempData = await departmentListService()
      this.managerList = await departmentManagerListService()
      // 编辑部门时，获取部门详情回显数据
      if (type === 'edit') {
        const { name, code, managerId, introduce, pid } = await departmentDetailService(id)
        this.deptForm = { name, code, managerId, introduce, pid }
      }
    },
    // 关闭以及重置表单
    handleClose() {
      this.isOpen = false
      this.eventType = ''
      this.currentNodeId = ''
      this.verifyTempData = {}
      this.$refs.deptFormRef.resetFields()
    },
    // 表单提交操作
    handleSubmit() {
      this.$refs.deptFormRef.validate(async valid => {
        if (!valid) return
        // 表单验证通过，提交数据
        // 添加部门
        if (this.eventType === 'add') {
          this.isLoading = true
          try {
            await departmentAddService({ ...this.deptForm, pid: this.currentNodeId })
            this.isLoading = false
            this.handleClose()
            Message.success('添加部门成功')
            this.$emit('updateDepartment')
          } catch (error) {
            this.isLoading = false
          } finally {
            this.isLoading = false
          }
        }
        // 编辑部门
        if (this.eventType === 'edit') {
          this.isLoading = true
          try {
            await departmentUpdateService({ ...this.deptForm, id: this.currentNodeId })
            this.isLoading = false
            this.handleClose()
            Message.success('编辑部门成功')
            this.$emit('updateDepartment')
          } catch (error) {
            this.isLoading = false
          } finally {
            this.isLoading = false
          }
        }
      })
    },
    // 删除部门
    async handleDelete(id) {
      await departmentDeleteService(id)
    }
  }
}
</script>

<script setup>
</script>
